<template>
  <!-- 已邮寄 -->
  <el-dialog :model-value="expressDeliveryDialogVisible" title="单号填写" width="520"
    :before-close="expressDeliveryBeforeClose">
    <el-form ref="expressDeliveryRef" :model="expressDelivery" style="width: 100%" :inline="true"
      :rules="expressDeliveryrules" label-width="130px" @submit.prevent>

      <el-row class="hm-row3" :gutter="60">
        <el-col :span="24">
          <el-form-item label="快递单号" prop="trackingNumber">
            <el-input v-model="expressDelivery.trackingNumber" placeholder="请输入快递单号" clearable style="width: 220px;"
              @input="handleTrackingNumberChange" /> <el-button type="primary" plain
              style="width: 50px; margin-left:10px" @click="transportOCR">识别</el-button>
          </el-form-item>

        </el-col>
      </el-row>

      <el-row class="hm-row3" :gutter="60">
        <el-col :span="24">
          <el-form-item label="快递公司" prop="shippingCompany">
            <el-select style="width: 220px" v-model="expressDelivery.shippingCompany" placeholder="请选择快递公司" filterable
              clearable :disabled="hm_express.length <= 1">
              <el-option v-for="item in hm_express" :key="item.value" :label="item.label" :value="item.label"
                @click="hmExpressCilck(item.logisticsTraceDetailList, item.logisticsType)"></el-option>
            </el-select>

          </el-form-item>
        </el-col>
      </el-row>
      <div v-if="remindStatus && !expressDelivery.shippingCompany"
        style="margin-left: 50px;margin-top:20px;border: none"><el-icon style="color: #FF6E00;margin-right: 10px;">
          <Warning />
        </el-icon><span style="color: #6F6F6F">{{ remindStatusText ? '识别到多个物流/快递公司,请确认' : '未查询到物流/快递公司,请核对单号' }}</span>
      </div>
    </el-form>
    <div class="dialog-footer">
      <el-button @click="expressDeliveryBeforeClose">取消</el-button>
      <el-button type="primary" :loading="buttonLoading" @click="expressDeliveryHandleSave(expressDeliveryRef)">
        确定
      </el-button>
    </div>
    <div v-if="props.isSample" class="dialog-title" @click="skipFilling">跳过填写</div>
  </el-dialog>
</template>
<script setup name="Mailed" lang="ts">
import { ElMessage, FormInstance } from 'element-plus'
import { editOne, getDeliveryInfo, addExpress, skipExpress } from '@/api/group/product/index'
const { proxy } = getCurrentInstance() as any;
// const { hm_express } = toRefs<any>(proxy?.useDict('hm_express'));
// 定义 Column 类型
interface Column {
  label: string;
  value: string;
  logisticsTraceDetailList: any[];
  logisticsType: string;
}
const hm_express = ref<Column[]>([

])
const buttonLoading = ref(false);
// isSample 是否补样
// 补样邀约 productId
const props = defineProps(['expressDeliveryDialogVisible', 'id', 'isSample', 'productId'])
const emit = defineEmits(['close', 'submit'])
const expressDeliveryRef = ref<FormInstance>()
const expressDelivery = ref<{ shippingCompany?: string, trackingNumber?: string, logisticsTraceDetailList?: any[], logisticsType?: string }>({
  shippingCompany: undefined,
  trackingNumber: undefined,
  logisticsTraceDetailList: [],
  logisticsType: undefined
})
// 快递单号效验
const validatorNumber = (ruls: any, val: string) => /^(?![a-zA-Z]+$)[a-zA-Z0-9]{8,30}$/.test(val);
const expressDeliveryrules = ref({
  shippingCompany: [
    { required: true, message: '请选择快递公司', trigger: 'change' },
  ],
  trackingNumber: [
    { required: true, message: '请输入快递单号', trigger: 'change' },
    { validator: validatorNumber, message: '请输入正确的快递单号', trigger: 'change' },
  ],
})
/** 关闭 */
const expressDeliveryBeforeClose = () => {
  expressDeliveryRef.value?.resetFields()
  emit('close')
}
/** 提交 */
const expressDeliveryHandleSave = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      buttonLoading.value = true
      try {
        // 补样的物流单号提交
        if (props.isSample) {
          await addExpress({ id: props.id, productId: props.productId, expressCompany: expressDelivery.value.shippingCompany, expressNumber: expressDelivery.value.trackingNumber, ...expressDelivery.value })
        } else {// 商品表的物流单号提交
          await editOne({ ...expressDelivery.value, id: props.id })
        }
        //清理相关数据
        await handleTrackingNumberChange()
        ElMessage.success('填写单号成功')
        expressDeliveryRef.value?.resetFields()
        buttonLoading.value = false
        emit('submit')
      } catch (err) {
        buttonLoading.value = false
        console.error(err)
      }
    }
  })
}
//识别快递单号
const transportOCR = async () => {
  remindStatus.value = false
  console.log('开始识别:', { orderNo: expressDelivery.value.trackingNumber })
  await expressDeliveryClean()
  let res = await getDeliveryInfo({ orderNo: expressDelivery.value.trackingNumber })
  console.log('识别结果:', res)
  if (res.code != 200 || res.data == null) {
    // showFailToast({ type: 'fail', message: '该订单号未查询到物流信息' });
    remindStatus.value = true
    remindStatusText.value = false
    return
  }
  if (res.data.info.length >= 2) {
    console.log("存在多条物流信息:", res.data.info)
    res.data.info.forEach((element: any) => {
      let ele: Column = {
        label: element.logisticsCompanyName || element.cpCode,  // 设置默认值
        value: element.cpCode,  // 设置默认值
        logisticsTraceDetailList: element.logisticsTraceDetailList || [],
        logisticsType: element.cpCode
      };
      hm_express.value.push(ele);
      // showFailToast({ type: 'fail', message: '快递存在多条,请手动选择' });
    });
    console.log("多条物流信息：", hm_express.value)
    remindStatus.value = true
    remindStatusText.value = true
    console.log("多条物流信息状态：", remindStatus.value)
  } else {
    expressDelivery.value.shippingCompany = res.data.info[0].logisticsCompanyName || res.data.info[0].cpCode
    expressDelivery.value.logisticsTraceDetailList = res.data.info[0].logisticsTraceDetailList || []
    expressDelivery.value.logisticsType = res.data.info[0].cpCode
  }
}
//清空缓存数据
const expressDeliveryClean = async () => {
  expressDelivery.value.logisticsTraceDetailList = []
  expressDelivery.value.logisticsType = undefined
  expressDelivery.value.shippingCompany = undefined
  hm_express.value = []
}

//提醒状态和文字
const remindStatus = ref(false)
const remindStatusText = ref(true)

//订单号发生变化清除缓存数据
const handleTrackingNumberChange = async () => {
  expressDelivery.value.shippingCompany = ''
  expressDelivery.value.logisticsType = ''
  expressDelivery.value.logisticsTraceDetailList = []
  remindStatus.value = false
  hm_express.value = []
}
//快递选择点击事件
const hmExpressCilck = async (logisticsTraceDetailList: any, logisticsType: any) => {
  const raw = toRaw(logisticsTraceDetailList)
  console.log("传递的值", raw, logisticsType)
  expressDelivery.value.logisticsTraceDetailList = raw
  expressDelivery.value.logisticsType = logisticsType
}
/** 跳过填写 */
const skipFilling = async () => {
  await skipExpress({ id: props.id, productId: props.productId, })
  //清理相关数据
  await handleTrackingNumberChange()
  ElMessage.success('跳过成功')
  expressDeliveryRef.value?.resetFields()
  buttonLoading.value = false
  emit('submit')
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  align-items: center;

}

.dialog-title {
  font-size: 14px;
  color: #666666;
  text-align: center;
  margin-top: 10px;
  text-decoration: underline;
  cursor: pointer;
}
</style>
